package com.lingz.manager.common.utils;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

public class MyWebSocketClient extends WebSocketClient {

    //用来接收数据
    private String excptMessage;

    //构造方法
    public MyWebSocketClient(URI serverUri) {
        super(serverUri);
        excptMessage = null;
    }

    //连接建立成功时调用该方法
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        System.out.println("连接成功！");
    }

    //收到来自服务端的消息时调用该方法
    @Override
    public void onMessage(String s) {
        System.out.println("收到消息：" + s);
        this.excptMessage = s;
        close();
        return;
    }

    //连接关闭时调用该方法
    @Override
    public void onClose(int i, String s, boolean b) {
        System.out.println("连接已断开！");
    }

    //出现错误时调用该方法
    @Override
    public void onError(Exception e) {
        System.out.println("连接出现错误！");
    }

    //发送消息
    public void sendMessage(String message){
        this.send(message);
        System.out.println("已发送消息：" + message);
    }

    //获取接收到的信息
    public String getExcptMessage() {
        if(excptMessage != null){
            String message = new String(excptMessage);
            excptMessage = null;
            return message;
        }
        return null;
    }
}